<?php
require('common.php');

function order_by_default($bonus_field)
{
	$beginning_string = 'ORDER BY ';
	if (strpos($bonus_field, '=\'') !== FALSE)
	{
		$beginning_point = strpos($bonus_field, $beginning_string) + strlen($beginning_string);
		$column = substr($bonus_field, $beginning_point); 

		return $column;
	} 
}
// list all of the fields in this table as an ordered list
function all_fields($order, $table, $default)
{
	$result = sql_exec("SHOW COLUMNS FROM $table");
	
	if (mysql_num_rows($result) > 0)
	{
		$dropdown = "<select name=\"$order\">\n";
		while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
		{
			$field_name = $row['Field'];
			$selected_toggle = ($default == $field_name) ? " selected " : "";
			$dropdown .= '<option' . $selected_toggle . ">$field_name</option>\n";
		}
		$dropdown .= "</select>\n";
		return $dropdown;
	} else {
		die("this table is empty.");
	}
}

// BEGIN EXECUTION

$userno = $user . 'no';
$instance = sql_row1("SELECT * FROM Instances WHERE User='$user' AND Domain='$domain' AND Line_Number='$line'");
//die(var_dump($instance));
$parsed = parse_query($instance['Bonus_Field']);
//die(var_dump($parsed));

// if the form was submitted, store the values
if (!empty($G['save']))
{
	// store it in the instance
	$table = $parsed['table'];
	$order = $G['order'];
	$ascending = $G['ascending'];
	$sql = "UPDATE Instances SET Bonus_Field='SELECT * FROM $table ORDER BY $order $ascending' WHERE User='$user' AND Domain='$domain' AND Line_Number='$line ORDER BY $order $ascending'";
	//die($sql);
	mysql_query($sql) or die(mysql_error());
	update($user, $domain, $line);
	header("Location: edit_page.php?domain=$domain");
}

html_header("go through a table");
?>

<body>

<div id="container">

<?php header_div(); ?>

<div id="body">

<h3>Go Through <?php echo remove_userno($parsed['table']); ?></h3>

<form action="go_through_table.php" method="get">
<input type="hidden" name="domain" value="<?php echo $domain; ?>" />
<input type="hidden" name="line" value="<?php echo $line; ?>" />

<p>Order By: <?php echo all_fields('order', $parsed['table'], $parsed['order_by']); ?>
<select name="ascending"><option value="ASC" >Going Up</option><option value="DESC">Going Down</option></select>
<p><input type="submit" name="save" value="save" /></p>
</form>

<p>
<form action="delete_instance.php" method="get">
<input type="hidden" name="domain" value="<?php echo $domain; ?>" />
<input type="hidden" name="line" value="<?php echo $line; ?>" />
<input type="submit" value="delete">
</form>
</p>

<?php echo footer(); ?>

</div>

</div>
</body>
</html>
